<!doctype html>
<head>
	<title>Sphere Example</title>
	<script src="../dist/threebox.js" type="text/javascript"></script>
	<script src="config.js"></script>

	<script src='https://api.mapbox.com/mapbox-gl-js/v0.50.0/mapbox-gl.js'></script>
	<link href='https://api.mapbox.com/mapbox-gl-js/v0.50.0/mapbox-gl.css' rel='stylesheet' />
	<style>
		body,
		html {
			width: 100%;
			height: 100%;
			margin: 0;
		}
		#map {
			width: 100%;
			height: 100%;
		}
	</style>
</head>

<body>
	<div id='map' class='map'></div>
	<script>
		mapboxgl.accessToken = config.accessToken;
		// var origin = [-122.4340, 37.7353, 500];
		var origin = [122, 37.7353, 500];
		var map = new mapboxgl.Map({
			container: 'map',
			style: 'mapbox://styles/mapbox/light-v9',
			center: origin,
			zoom: 4,
			pitch: 30
		});

		function getSpherePos(){
			var spherePos = sphere.matrixWorld.getPosition()
			var posVec4 = new THREE.Vector4(spherePos.x, spherePos.y, spherePos.z);
			posVec4.applyMatrix4(camera.matrixWorldInverse)
			posVec4.applyMatrix4(camera.projectionMatrix);
			var windowWidth = document.body.clientWidth;
			var windowWidthHalf = windowWidth / 2;
			var windowHeight = document.body.clientHeight;
			var windowHeightHalf = windowHeight / 2;
			var screemX = windowWidthHalf + windowWidthHalf * posVec4.x / posVec4.w;
			var screemY = windowHeightHalf - windowHeightHalf * posVec4.y/ posVec4.w;
			console.dir('x ' + screemX);
			console.dir('y ' + screemY);
		}

		map.on('style.load', function () {
			map.addLayer({
				id: 'custom_layer',
				type: 'custom',
				onAdd: function (map, mbxContext) {
					tb = new Threebox(
						map,
						mbxContext,
						{ defaultLights: true }
					);
					window.sphere = tb.sphere({
						color: 'red',
						material: 'MeshStandardMaterial',
						radius: 5000
				    }).setCoords(origin);
					tb.add(sphere);
				},
				render: function (gl, matrix) {
					tb.update();
					getSpherePos()
				}
			})
		});

	</script>
</body>